import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../models/question.dart';
import '../models/answer.dart';
import '../services/data_persistence_manager.dart';
import 'global_state_coordinator.dart';

class DiscussionHubProvider extends ChangeNotifier {
  final DataPersistenceManager _persistenceManager;
  final GlobalStateCoordinator _globalStateCoordinator;

  List<DiscussionTopic> _topicCollection = [];
  bool _isDataLoading = false;
  String? _errorMessage;
  DiscussionTopic? _selectedTopic;

  DiscussionHubProvider(
    this._persistenceManager,
    this._globalStateCoordinator,
  ) {
    _initializeWithSampleData();
  }

  List<DiscussionTopic> get topicCollection =>
      List.unmodifiable(_topicCollection);
  bool get isDataLoading => _isDataLoading;
  String? get errorMessage => _errorMessage;
  DiscussionTopic? get selectedTopic => _selectedTopic;

  Future<void> _initializeWithSampleData() async {
    _isDataLoading = true;
    notifyListeners();

    try {
      final savedDataString = _persistenceManager.getString(
        'discussion_topics',
      );

      if (savedDataString != null && savedDataString.isNotEmpty) {
        final savedDataList = jsonDecode(savedDataString) as List;
        _topicCollection =
            savedDataList
                .map((item) => DiscussionTopic.fromDataMap(item))
                .toList();
      } else {
        _topicCollection = _generateSampleTopics();
        await _saveTopicsToStorage();
      }

      _errorMessage = null;
    } catch (e) {
      _errorMessage = 'Failed to load discussion topics: $e';
      _topicCollection = _generateSampleTopics();
    } finally {
      _isDataLoading = false;
      notifyListeners();
    }
  }

  List<DiscussionTopic> _generateSampleTopics() {
    final now = DateTime.now();
    final defaultUsers = _globalStateCoordinator.defaultUsers;

    if (defaultUsers.isEmpty) return [];

    final user1 =
        defaultUsers.isNotEmpty
            ? defaultUsers[0]
            : _globalStateCoordinator.getRandomDefaultUser();
    final user2 =
        defaultUsers.length > 1
            ? defaultUsers[1]
            : _globalStateCoordinator.getRandomDefaultUser();
    final user3 =
        defaultUsers.length > 2
            ? defaultUsers[2]
            : _globalStateCoordinator.getRandomDefaultUser();
    final user4 =
        defaultUsers.length > 3
            ? defaultUsers[3]
            : _globalStateCoordinator.getRandomDefaultUser();

    return [
      DiscussionTopic(
        topicId: 'topic_001',
        topicTitle:
            'How Can I Switch Between Barre Chords More Smoothly? My Fingers Feel Stiff When Transitioning.',
        topicDescription:
            'I\'ve been practicing guitar for about 6 months now and I\'m struggling with barre chord transitions. My fingers get stiff and I can\'t seem to move between different barre chord positions smoothly. Any tips or exercises that could help?',
        creatorId: user1.id,
        creatorDisplayName: user1.userName,
        creatorProfileImage: user1.avatar,
        creationTime: now.subtract(const Duration(days: 2)),
        lastUpdateTime: now.subtract(const Duration(hours: 3)),
        viewerCount: 1266,
        supportCount: 15,
        categoryTags: ['guitar', 'barre-chords', 'technique'],
        responseList: [
          ResponseItem(
            responseId: 'response_001',
            topicId: 'topic_001',
            responseText:
                'Practice finger exercises daily! Start with simple stretches and gradually work up to full barre chords. Also, make sure your thumb position is correct behind the neck.',
            contributorId: user2.id,
            contributorDisplayName: user2.userName,
            contributorProfileImage: user2.avatar,
            publishedTime: now.subtract(const Duration(hours: 5)),
            lastModifiedTime: now.subtract(const Duration(hours: 5)),
            approvalCount: 8,
            isMarkedUseful: true,
          ),
          ResponseItem(
            responseId: 'response_002',
            topicId: 'topic_001',
            responseText:
                'Try practicing chord transitions without pressing down on the strings first. Just get your fingers used to the shapes and movements. Once muscle memory develops, add the pressure.',
            contributorId: user4.id,
            contributorDisplayName: user4.userName,
            contributorProfileImage: user4.avatar,
            publishedTime: now.subtract(const Duration(hours: 3)),
            lastModifiedTime: now.subtract(const Duration(hours: 3)),
            approvalCount: 5,
          ),
          ResponseItem(
            responseId: 'response_003',
            topicId: 'topic_001',
            responseText:
                'Make sure your guitar is properly set up! High action can make barre chords much harder than they need to be. Consider getting a professional setup.',
            contributorId:
                defaultUsers.length > 4 ? defaultUsers[4].id : user1.id,
            contributorDisplayName:
                defaultUsers.length > 4
                    ? defaultUsers[4].userName
                    : user1.userName,
            contributorProfileImage:
                defaultUsers.length > 4 ? defaultUsers[4].avatar : user1.avatar,
            publishedTime: now.subtract(const Duration(hours: 1)),
            lastModifiedTime: now.subtract(const Duration(hours: 1)),
            approvalCount: 3,
          ),
        ],
      ),
      DiscussionTopic(
        topicId: 'topic_002',
        topicTitle:
            'I\'m Struggling To Find The Strumming Pattern For This Song. Does Anyone Have Suggestions Or A Tutorial Link?',
        topicDescription:
            'I\'ve been trying to learn "Wonderwall" by Oasis but I can\'t get the strumming pattern right. I\'ve watched several YouTube videos but still struggling. Can someone break it down or recommend a good tutorial?',
        creatorId: user3.id,
        creatorDisplayName: user3.userName,
        creatorProfileImage: user3.avatar,
        creationTime: now.subtract(const Duration(days: 1)),
        lastUpdateTime: now.subtract(const Duration(hours: 1)),
        viewerCount: 208,
        supportCount: 12,
        categoryTags: ['strumming', 'oasis', 'tutorial'],
        responseList: [
          ResponseItem(
            responseId: 'response_004',
            topicId: 'topic_002',
            responseText:
                'The strumming pattern for Wonderwall is: D-D-U-D-U-D-U (Down-Down-Up-Down-Up-Down-Up). Start slow and focus on the rhythm before speeding up.',
            contributorId: user2.id,
            contributorDisplayName: user2.userName,
            contributorProfileImage: user2.avatar,
            publishedTime: now.subtract(const Duration(hours: 4)),
            lastModifiedTime: now.subtract(const Duration(hours: 4)),
            approvalCount: 12,
            isMarkedUseful: true,
          ),
          ResponseItem(
            responseId: 'response_005',
            topicId: 'topic_002',
            responseText:
                'Try using a metronome! Set it to 60 BPM and practice the pattern slowly. Once you get comfortable, gradually increase the tempo.',
            contributorId: user1.id,
            contributorDisplayName: user1.userName,
            contributorProfileImage: user1.avatar,
            publishedTime: now.subtract(const Duration(hours: 2)),
            lastModifiedTime: now.subtract(const Duration(hours: 2)),
            approvalCount: 7,
          ),
          ResponseItem(
            responseId: 'response_006',
            topicId: 'topic_002',
            responseText:
                'Check out JustinGuitar on YouTube - he has an excellent tutorial specifically for Wonderwall with clear strumming demonstrations.',
            contributorId:
                defaultUsers.length > 5 ? defaultUsers[5].id : user4.id,
            contributorDisplayName:
                defaultUsers.length > 5
                    ? defaultUsers[5].userName
                    : user4.userName,
            contributorProfileImage:
                defaultUsers.length > 5 ? defaultUsers[5].avatar : user4.avatar,
            publishedTime: now.subtract(const Duration(minutes: 45)),
            lastModifiedTime: now.subtract(const Duration(minutes: 45)),
            approvalCount: 9,
          ),
        ],
      ),
      DiscussionTopic(
        topicId: 'topic_003',
        topicTitle:
            "What's A Good Beginner-Friendly Amp For Practicing Electric Guitar At Home Without Disturbing Others?",
        topicDescription:
            "I just got my first electric guitar and I need an amp for home practice. I live in an apartment so I need something that won't disturb my neighbors but still sounds good. Budget is around \$200. Any recommendations?",
        creatorId: user4.id,
        creatorDisplayName: user4.userName,
        creatorProfileImage: user4.avatar,
        creationTime: now.subtract(const Duration(hours: 8)),
        lastUpdateTime: now.subtract(const Duration(hours: 8)),
        viewerCount: 309,
        supportCount: 7,
        categoryTags: ['electric-guitar', 'amplifier', 'beginner'],
        responseList: [
          ResponseItem(
            responseId: 'response_007',
            topicId: 'topic_003',
            responseText:
                'I highly recommend the Yamaha THR10II! It\'s perfect for apartment practice with great headphone output and built-in effects. Around \$180 and very neighbor-friendly.',
            contributorId: user2.id,
            contributorDisplayName: user2.userName,
            contributorProfileImage: user2.avatar,
            publishedTime: now.subtract(const Duration(hours: 6)),
            lastModifiedTime: now.subtract(const Duration(hours: 6)),
            approvalCount: 15,
            isMarkedUseful: true,
          ),
          ResponseItem(
            responseId: 'response_008',
            topicId: 'topic_003',
            responseText:
                'Consider the Boss Katana Mini - it\'s compact, has great tone at low volumes, and fits your budget perfectly. Plus it has an aux input for playing along with songs.',
            contributorId: user1.id,
            contributorDisplayName: user1.userName,
            contributorProfileImage: user1.avatar,
            publishedTime: now.subtract(const Duration(hours: 4)),
            lastModifiedTime: now.subtract(const Duration(hours: 4)),
            approvalCount: 11,
          ),
          ResponseItem(
            responseId: 'response_009',
            topicId: 'topic_003',
            responseText:
                'Don\'t forget about audio interfaces! You can plug directly into your computer and use amp simulation software like GarageBand or Amplitube. Very quiet and versatile.',
            contributorId: user3.id,
            contributorDisplayName: user3.userName,
            contributorProfileImage: user3.avatar,
            publishedTime: now.subtract(const Duration(hours: 2)),
            lastModifiedTime: now.subtract(const Duration(hours: 2)),
            approvalCount: 8,
          ),
          ResponseItem(
            responseId: 'response_010',
            topicId: 'topic_003',
            responseText:
                'The Fender Mustang LT25 is another great option in your price range. It has tons of presets and you can practice silently with headphones.',
            contributorId:
                defaultUsers.length > 4 ? defaultUsers[4].id : user2.id,
            contributorDisplayName:
                defaultUsers.length > 4
                    ? defaultUsers[4].userName
                    : user2.userName,
            contributorProfileImage:
                defaultUsers.length > 4 ? defaultUsers[4].avatar : user2.avatar,
            publishedTime: now.subtract(const Duration(minutes: 30)),
            lastModifiedTime: now.subtract(const Duration(minutes: 30)),
            approvalCount: 6,
          ),
        ],
      ),
    ];
  }

  /// 添加新话题
  Future<void> createNewTopic({
    required String title,
    required String description,
    required String creatorId,
    required String creatorName,
    required String creatorAvatar,
    List<String> tags = const [],
  }) async {
    _isDataLoading = true;
    notifyListeners();

    try {
      final newTopic = DiscussionTopic(
        topicId: 'topic_${DateTime.now().millisecondsSinceEpoch}',
        topicTitle: title,
        topicDescription: description,
        creatorId: creatorId,
        creatorDisplayName: creatorName,
        creatorProfileImage: creatorAvatar,
        creationTime: DateTime.now(),
        lastUpdateTime: DateTime.now(),
        categoryTags: tags,
      );

      _topicCollection.insert(0, newTopic);
      await _saveTopicsToStorage();
      _errorMessage = null;
    } catch (e) {
      _errorMessage = 'Failed to create topic: $e';
    } finally {
      _isDataLoading = false;
      notifyListeners();
    }
  }

  /// 添加回复
  Future<void> addResponseToTopic({
    required String topicId,
    required String responseText,
    required String contributorId,
    required String contributorName,
    required String contributorAvatar,
  }) async {
    _isDataLoading = true;
    notifyListeners();

    try {
      final topicIndex = _topicCollection.indexWhere(
        (topic) => topic.topicId == topicId,
      );
      if (topicIndex == -1) {
        throw Exception('Topic not found');
      }

      final newResponse = ResponseItem(
        responseId: 'response_${DateTime.now().millisecondsSinceEpoch}',
        topicId: topicId,
        responseText: responseText,
        contributorId: contributorId,
        contributorDisplayName: contributorName,
        contributorProfileImage: contributorAvatar,
        publishedTime: DateTime.now(),
        lastModifiedTime: DateTime.now(),
      );

      final updatedTopic = _topicCollection[topicIndex].createModifiedVersion(
        responseList: [
          ..._topicCollection[topicIndex].responseList,
          newResponse,
        ],
        lastUpdateTime: DateTime.now(),
      );

      _topicCollection[topicIndex] = updatedTopic;
      await _saveTopicsToStorage();
      _errorMessage = null;
    } catch (e) {
      _errorMessage = 'Failed to add response: $e';
    } finally {
      _isDataLoading = false;
      notifyListeners();
    }
  }

  Future<void> incrementTopicViews(String topicId) async {
    try {
      final topicIndex = _topicCollection.indexWhere(
        (topic) => topic.topicId == topicId,
      );
      if (topicIndex != -1) {
        final updatedTopic = _topicCollection[topicIndex].createModifiedVersion(
          viewerCount: _topicCollection[topicIndex].viewerCount + 1,
        );
        _topicCollection[topicIndex] = updatedTopic;
        await _saveTopicsToStorage();
        notifyListeners();
      }
    } catch (e) {
      debugPrint('Failed to increment views: $e');
    }
  }

  /// 设置选中的话题
  void selectTopic(DiscussionTopic? topic) {
    _selectedTopic = topic;
    notifyListeners();
  }

  /// 删除话题
  Future<void> deleteTopic(String topicId) async {
    _isDataLoading = true;
    notifyListeners();

    try {
      _topicCollection.removeWhere((topic) => topic.topicId == topicId);
      await _saveTopicsToStorage();
      _errorMessage = null;
    } catch (e) {
      _errorMessage = 'Failed to delete topic: $e';
    } finally {
      _isDataLoading = false;
      notifyListeners();
    }
  }

  /// 删除回答
  Future<void> deleteResponse(String topicId, String responseId) async {
    _isDataLoading = true;
    notifyListeners();

    try {
      final topicIndex = _topicCollection.indexWhere(
        (topic) => topic.topicId == topicId,
      );
      if (topicIndex != -1) {
        final currentTopic = _topicCollection[topicIndex];
        final updatedResponseList =
            currentTopic.responseList
                .where((response) => response.responseId != responseId)
                .toList();

        final updatedTopic = currentTopic.createModifiedVersion(
          responseList: updatedResponseList,
          lastUpdateTime: DateTime.now(),
        );

        _topicCollection[topicIndex] = updatedTopic;
        await _saveTopicsToStorage();
      }
      _errorMessage = null;
    } catch (e) {
      _errorMessage = 'Failed to delete response: $e';
    } finally {
      _isDataLoading = false;
      notifyListeners();
    }
  }

  Future<void> _saveTopicsToStorage() async {
    try {
      final dataList =
          _topicCollection.map((topic) => topic.toDataMap()).toList();
      final dataString = jsonEncode(dataList);
      await _persistenceManager.setString('discussion_topics', dataString);
    } catch (e) {
      debugPrint('Failed to save topics: $e');
    }
  }

  /// 刷新数据
  Future<void> refreshData() async {
    await _initializeWithSampleData();
  }

  /// 清除错误信息
  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }
}
